package com.ym521.emojipack.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.style.DynamicDrawableSpan;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatMultiAutoCompleteTextView;

import com.ym521.emojipack.EmojiPackHelper;
import com.ym521.emojipack.R;
import com.ym521.emojipack.emoji.EmojiPackHandler;

/**
 * @author Ym
 */
public final class EmojiPackMultiAutoCompleteTextView extends AppCompatMultiAutoCompleteTextView {
    private int mEmojiconSize;
    private int mEmojiconAlignment;
    private int mEmojiconTextSize;
    private boolean mUseSystemDefault = false;

    public EmojiPackMultiAutoCompleteTextView(Context context) {
        super(context);
        init(null);
    }

    public EmojiPackMultiAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public EmojiPackMultiAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        float textSize = getTextSize();
        //默认放大 20%
        float packSize = textSize * EmojiPackHelper.Builder.EMOJI_ENLARGE;
        mEmojiconSize = (int) packSize;
        mEmojiconTextSize = (int) textSize;
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.EmojiPackMultiAutoCompleteTextView);
            mEmojiconAlignment = a.getInt(R.styleable.EmojiPackMultiAutoCompleteTextView_emojiPackAlignment, DynamicDrawableSpan.ALIGN_CENTER);
            mUseSystemDefault = a.getBoolean(R.styleable.EmojiPackMultiAutoCompleteTextView_emojiPackUseSystemDefault, false);
            a.recycle();
        }
        setText(getText());
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        updateText();
    }

    /**
     * Set the size of emojicon in pixels.
     */
    public void setEmojiconSize(int pixels) {
        mEmojiconSize = pixels;

        updateText();
    }

    private void updateText() {
        EmojiPackHandler.addEmojis(getContext(), getText(), mEmojiconSize, mEmojiconAlignment, mEmojiconTextSize, mUseSystemDefault);
    }

    /**
     * Set whether to use system default emojicon
     */
    public void setUseSystemDefault(boolean useSystemDefault) {
        mUseSystemDefault = useSystemDefault;
    }
}
